package grouplife::Controller::Stores;
use Moose;
use namespace::autoclean;
use Catalyst::Request::Upload;
use String::Random;
use File::Basename;

use grouplife::Model::Category::CategoryModel;
use grouplife::Model::Source::SourceModel;
use grouplife::Model::Store::StoreSearchModel;
use grouplife::Model::Store::StoreCreateModel;
use grouplife::Model::Tuan::TuansSearchModel;
use grouplife::Model::Comments::CommentsForStoreModel;
use grouplife::Model::UserStore::UserStoreModel;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::CommentedItem::CommentedItemModel;
use grouplife::Model::Leimu::LeimuModel;
use grouplife::Model::UserTuan::UserTuanModel;
use grouplife::Model::CategoryStore::CategoryStoreModel;
use grouplife::Model::University::UniversityModel;
use Util::Email::SendEmail;

BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Stores - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    $c->response->body('Matched grouplife::Controller::Stores in Stores.');
}

sub list :Local {
        my ($self, $c) = @_;

        $c->stash(login_user => $c->session->{login_user},
		cats => [$c->model('Category::CategoryModel')->get_all],
		javascript => '/store/store_list.js',
		template => 'stores/list.tt2');
}

sub store_search:Local {
        my ($self, $c) = @_;

        my $name = $c->request->params->{content} || '';
        my $category = $c->request->params->{category} || '';
        my $category_name = $c->request->params->{category_name} || '';
	my %leimu_hash;
        my @leimus = $c->model('Leimu::LeimuModel')->get_all();
        foreach my $leimu(@leimus) {
                $leimu_hash{$leimu->id}{"leimu_name"} = $leimu->name;
                my @cats = $c->model('Category::CategoryModel')->get_cat_by_leimuid($leimu->id);
                foreach my $cat (@cats) {
                        $leimu_hash{$leimu->id}{"cats"}{$cat->id}{"name"} = $cat->name;
                        $leimu_hash{$leimu->id}{"cats"}{$cat->id}{"count"} =  $c->model('Store::StoreSearchModel')->store_total('', $cat->id);
                }
        }

	my @top_cats =  $c->model('CategoryStore::CategoryStoreModel')->get_top_ten();
        my %top_ten_cats;
        my $count = 1;
        foreach (@top_cats) {
                $top_ten_cats{"$count"}{"category_id"} =  $_->category_id;
                $top_ten_cats{"$count"}{"name"} =  $_->get_column("category_name");
                $top_ten_cats{"$count"}{"count"} =  $_->get_column("store_count");
                $count ++;
        }


	if($category eq '') {
		$category = '0';
		$category_name = '全部分类';
	}	
        $c->stash(
		login_user => $c->session->{login_user},
		javascript => '/store/store_search.js',
		leimu_hash => \%leimu_hash,
		top_ten_cats => \%top_ten_cats,
		title => "搜索商品",
		category => $category,
		content => $name,
		category_name => $category_name,
		css => 'store_search.css',
		cats => [$c->model('Category::CategoryModel')->get_all],
		template => 'stores/list.tt2');
}

sub store_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $name = $c->request->params->{name} || '';
        my $category = $c->request->params->{category};

        my $page = $start_index / 10;
        $page = $page + 1;

        $c->stash(
                login_user => $c->session->{login_user},
                nowrapper => 1,
                template => 'stores/store_search.tt2',
		stores => [$c->model('Store::StoreSearchModel')->store_paging($name, $category, $page)]
        );
}

#Autocomplete in store search page
sub store_names:Local {
        my ($self, $c) = @_;
        my $p = $c->request->params->{q} || '';
        $c->res->output($c->model('Store::StoreSearchModel')->get_names_in_json($p));
}

sub store_total:Local {
        my ($self, $c) = @_;
        my $name = $c->request->params->{name} || '';
        my $category = $c->request->params->{category};
	$c->res->output($c->model('Store::StoreSearchModel')->store_total($name, $category));
}

sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
        my ($self, $c) = @_;

        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
                return 0;
        }

	my $host_uri = $c->config->{host_uri};
	$c->stash(login_user => $c->session->{login_user},
		cats => [$c->model('Category::CategoryModel')->get_all],
		sources => [$c->model('Source::SourceModel')->get_all],
		title => '创建网店',
		javascript => '/store/form_create.js',
		host_uri => $host_uri,
		css => 'create_new_store.css',
		template => 'stores/form_create.tt2');
}

sub form_create_fail :Chained('base') :PathPart('form_create_fail') :Args(0) {
        my ($self, $c) = @_;

        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
                return 0;
        }

	my $name = $c->request->params->{chanpin_name} || '';
	$c->stash(login_user => $c->session->{login_user},
		cats => [$c->model('Category::CategoryModel')->get_all],
		sources => [$c->model('Source::SourceModel')->get_all],
		title => '创建网店',
		javascript => '/store/form_create.js',
		css => 'create_new_store.css',
		template => 'stores/form_create.tt2',
		store_name => $c->request->params->{storename},	
		category => $c->request->params->{category},
		price => $c->request->params->{price},
		threshold_num => $c->request->params->{threshold_num},
		bulletin => $c->request->params->{bulletin},
		neirong => $c->request->params->{description},
		location=> $c->request->params->{location} 
		);
}

sub search_stores :Chained('base') :PathPart('search_stores'){
	my ($self, $c) = @_;

	my $name = $c->request->params->{name} || '';
	my $category = $c->request->params->{category} || '';
	$c->response->redirect($c->uri_for($c->controller('Category')->action_for('search_stores'), [$category]));
}

sub time_out :Local{
	my ($self, $c) = @_;

	my $tuan_id = $c->request->params->{tuan_id} || '';
	my $status = $c->request->params->{tuanstatus} || '';
	$c->res->output($c->model('Tuan::TuansSearchModel')->get_time_out($tuan_id, $status));
}

sub form_create_do :Chained('base') :PathPart('form_create_do'){
	my ($self, $c) = @_;

	my $name = $c->request->params->{storename} || '';
	my $category = $c->request->params->{storeCategory} || '';
	my $description = $c->request->params->{neirong} || '';
	my $location = $c->request->params->{location} || '';
	my $price = $c->request->params->{price} || '';
	my $threshhold_num = $c->request->params->{threshhold_num} || '';
	my $bulletin = $c->request->params->{bulletin} || '';

	my @message;
	#unless($price =~ /^[1-9]\d*\.[0-9]\d*$/) {
	unless($price =~ /^[1-9]\d*\.?\d*$/) {
                my $text = "你输入的商品价格不是合法的数字";
		push(@message, $text);
	}
	unless($threshhold_num =~ /^[1-9]\d*$/) {
                my $text = "你输入的最低参团人数不是合法的数字";
		push(@message, $text);
	}
        if(scalar(@message) != 0) {
                $c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@message);
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'stores/create_store_failed.tt2');
                $c->stash(storename => $name);
                $c->stash(category => $category);
                $c->stash(location => $location);
                $c->stash(bulletin => $bulletin);
                $c->stash(threshold_num => $threshhold_num);
                $c->stash(description => $description);
                $c->stash(price => $price);
	} else {
		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('2');
		my $upload = $c->request->upload('image');
		my $store = $c->model('Store::StoreCreateModel')->create($c->config->{image_path}, $c->user->get('id'), $upload, $name, $bulletin, $description, $commented_item->id, $location, $category, $price, $threshhold_num);

		$c->user->add_to_my_news({user_id=>$c->user->id, photo=>$c->user->photo, event_type_id=>2, me_name=>$c->user->username, target_id=>$store->id, target_name=>$store->name});
		$c->response->redirect($c->uri_for($c->controller('Stores')->action_for('store_info'), [$store->id]));
	}
}

sub update_store:Local{
	my ($self, $c) = @_;

	my $name = $c->request->params->{storename} || '';
	my $store_id = $c->request->params->{store_id};
	my $category = $c->request->params->{storeCategory} || '';
	my $description = $c->request->params->{neirong} || '';
	my $location = $c->request->params->{location} || '';
	my $price = $c->request->params->{price} || '';
	my $threshhold_num = $c->request->params->{threshhold_num} || '';
	my $bulletin = $c->request->params->{bulletin} || '';

	my @message;
	#unless($price =~ /^[1-9]\d*\.[0-9]\d*$/) {
	unless($price =~ /^[1-9]\d*\.?\d*$/) {
                my $text = "你输入的商品价格不是合法的数字";
		push(@message, $text);
	}
	unless($threshhold_num =~ /^[1-9]\d*$/) {
                my $text = "你输入的最低参团人数不是合法的数字";
		push(@message, $text);
	}
        if(scalar(@message) != 0) {
                $c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@message);
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'stores/create_store_failed.tt2');
                $c->stash(storename => $name);
                $c->stash(category => $category);
                $c->stash(location => $location);
                $c->stash(bulletin => $bulletin);
                $c->stash(threshold_num => $threshhold_num);
                $c->stash(description => $description);
                $c->stash(price => $price);
	} else {
		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('2');
		my $upload = $c->request->upload('image');
		my $store = $c->model('Store::StoreCreateModel')->update($c->config->{image_path}, $c->user->get('id'), $upload, $name, $bulletin, $description, $commented_item->id, $location, $category, $price, $threshhold_num, $store_id);

		$c->response->redirect($c->uri_for($c->controller('Stores')->action_for('store_info'), [$store->id]));
	}
}


sub base :Chained('/') :PathPart('stores') :CaptureArgs(0) {
        my ($self, $c) = @_;
}

sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
        my ($self, $c, $id) = @_;

        $c->stash(object => $c->model('Store::StoreSearchModel')->find($id));
}

sub delete:Local {
        my ($self, $c) = @_;

	my $store_id = $c->request->params->{store_id};
        my $tuan = $c->model('Store::StoreSearchModel')->find($store_id);

        my $image = $tuan->image;
	my $image_path = $c->config->{image_path};
	$tuan->delete();
        if(defined($image) && ($image ne "")){
                system("rm \"$image_path/small/$image\"");
                system("rm \"$image_path/big/$image\"");
        }
        $c->res->output("success");
}

sub xiajia:Local {
        my ($self, $c) = @_;

	my $store_id = $c->request->params->{store_id};
        my @user_stores = $c->model('UserStore::UserStoreModel')->get_all_members($store_id);
	for(@user_stores){
		$_->delete();
	}

        $c->res->output("success");
}

sub create_tuan : Local{
	my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	my $universities = $c->model('University::UniversityModel')->get_all;
	my $host_uri = $c->config->{host_uri};
	
	my @stores = $user->own_stores;
	my (%hash_shenpi, %hash_ongoing);
	foreach (@stores) {
		my $store_id = $_->id;

		my $shenpi = $c->model('Store::StoreSearchModel')->get_shenpi_tuans($store_id);
		my $shenpi_count = scalar (@$shenpi);
		$hash_shenpi{$store_id} = 1 if($shenpi_count != 0);

		my $on_going = $c->model('Store::StoreSearchModel')->get_ongoing_tuans($store_id);
		my $on_going_count= scalar (@$on_going);
		$hash_ongoing{$store_id} = 1 if($on_going_count != 0);
	}

	my $curr_time = `date --iso-8601=seconds`;
	$c->stash(login_user => $c->session->{login_user},
		javascript => '/store/create_tuan.js',
		css => 'create_new_tuan.css',
		universities => $universities,
		hash_shenpi => \%hash_shenpi,
		curr_time => $curr_time,
		hash_ongoing => \%hash_ongoing,
		host_uri => $host_uri,
		user => $user,
		template => "stores/create_tuan.tt2");

}

sub edit_tuan : Local{
	my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $tuan_id = $c->request->params->{tuan_id};
	my $tuan = $c->model('Tuan::TuansSearchModel')->find($tuan_id);
	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	my $universities = $c->model('University::UniversityModel')->get_all;
	my $tuan_universities = $c->model('University::UniversityModel')->get_all;
	
	my @stores = $user->own_stores;
	my (%hash_shenpi, %hash_ongoing);
	foreach (@stores) {
		my $store_id = $_->id;

		my $shenpi = $c->model('Store::StoreSearchModel')->get_shenpi_tuans($store_id);
		my $shenpi_count = scalar (@$shenpi);
		$hash_shenpi{$store_id} = 1 if($shenpi_count != 0);

		my $on_going = $c->model('Store::StoreSearchModel')->get_ongoing_tuans($store_id);
		my $on_going_count= scalar (@$on_going);
		$hash_ongoing{$store_id} = 1 if($on_going_count != 0);
	}

	my $curr_time = `date --iso-8601=seconds`;
	$c->stash(login_user => $c->session->{login_user},
		javascript => '/store/create_tuan.js',
		css => 'create_new_tuan.css',
		universities=>$universities,
		hash_shenpi => \%hash_shenpi,
		hash_ongoing => \%hash_ongoing,
		curr_time => $curr_time,
		user => $user,
		tuan => $tuan,
		template => "stores/edit_tuan.tt2");
}

sub edit_store : Local{
	my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $store_id = $c->request->params->{store_id};
	my $store = $c->model('Store::StoreSearchModel')->find($store_id);
	
	my $host_uri = $c->config->{host_uri};
	$c->stash(login_user => $c->session->{login_user},
		cats => [$c->model('Category::CategoryModel')->get_all],
		sources => [$c->model('Source::SourceModel')->get_all],
		title => '编辑商品',
		store => $store,
		javascript => '/store/form_create.js',
		host_uri => $host_uri,
		css => 'create_new_store.css',
		template => 'stores/edit_store.tt2');
}

sub join_store_login : Local{
	my ($self, $c) = @_;
       
        my $store_id= $c->request->params->{store_id};
        $c->response->redirect($c->uri_for('/login'));
        $c->flash->{redirect_after_login} = '' . $c->req->base . "stores/id/$store_id/store_info";
        return 0;
}

sub join_tuan : Local{
	my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $store_id= $c->request->params->{store_id};
	my $user_id= $c->request->params->{user_id};

	my @user_stores = $c->model('UserStore::UserStoreModel')->userstore_search($user_id, $store_id);
	unless(@user_stores > 0) {
		my $user = $c->model('Users::UsersSearchModel')->find($user_id);
		$user->add_to_user_stores({user_id=>$user_id, stores_id=>$store_id, notify_status=>'N', role=>'T'});
	} else {
		my $user_store = $user_stores[0];
		$c->log->error("count".@user_stores);
		if ($user_store->get_column("notify_status") eq 'Y') {
			$c->model('UserStore::UserStoreModel')->update_notify_status_to_no($store_id,$user_id);	
		}
	}
	
	#if more than 10 users want to buy this product, send a notification to owner
	my $unnotified_user_count = $c->model('UserStore::UserStoreModel')->get_unnotified_user($store_id)->count;
	my $threshold = $c->config->{user_notification_threshold};
	if($unnotified_user_count % $threshold == 0) {
		my $store = $c->model('Store::StoreSearchModel')->find($store_id);
		my $owner_id = $c->model('UserStore::UserStoreModel')->get_owner($store_id)->get_column("user_id")->first();					
		my $owner = $c->model('Users::UsersSearchModel')->find($owner_id);
		my $owner_name= $owner->get_column("username");
        	my $title = "更多人关注了您在随你团发布的商品";
        	my $sender = Util::Email::SendEmail->new();
        	my $template = "email/notifyOwner.html.tt";
        	my $store_url = $c->config->{store_info_uri} . "/" . $store_id . "/store_info";
        	my (%params, %options);
        	$options{INCLUDE_PATH} = $c->config->{email_template_path};
        	$params{username} = $owner_name;
        	$params{storename} = $store->get_column("name");
        	$params{usercount} = $unnotified_user_count;
        	$params{conf_url} = $store_url;
        	$params{approve_time} = `date`;
        	$sender->send($owner->get_column("email_address"), $title, $template, \%params, \%options);
	}

	$c->response->redirect($c->uri_for($c->controller('Stores')->action_for('store_info'), [$store_id]));
}

sub store_info :Chained('object') :PathPart('store_info') :Args(0) {
        my ($self, $c) = @_;
	
	$c->cache_page( $c->config->{time_out} );
	my $store_id = $c->stash->{object}->id;
	
	#S表示销售之中
	my $zhuangtai = 'S';
	my $login_user_role = 'X';
	my $create_time;
	my $create_user;
        my $user_store= $c->model('UserStore::UserStoreModel')->get_owner($c->stash->{object}->id);
	if($user_store->count() == 0) {
		#X表示已经下架
		$zhuangtai = 'X';
	} else {
		$create_time = $user_store->get_column('created')->first();
		$create_user = $c->model('Users::UsersSearchModel')->find($user_store->get_column('user_id')->first());
		unless (defined $c->session->{login_user}) {
		#This user did not login yet
			$login_user_role = 'U';
		} else {
			if($c->session->{login_user}->id eq $create_user->id) {
				$login_user_role = 'O';
			}
			elsif($c->model('UserStore::UserStoreModel')->userstore_search_by_status($c->session->{login_user}->id, $c->stash->{object}->id,'N','T')->count == 0) {
				$login_user_role = 'T';
			}
		}
        	$c->stash(create_user => $create_user);
        	$c->stash(create_time  => $create_time);
	}

	my $out_of_dates = $c->model('Store::StoreSearchModel')->get_outofdates_tuans($store_id);
	my $out_of_dates_count = scalar (@$out_of_dates);
	my $shenpi = $c->model('Store::StoreSearchModel')->get_shenpi_tuans($store_id);
	my $shenpi_count = scalar (@$shenpi);
	my $on_going = $c->model('Store::StoreSearchModel')->get_ongoing_tuans($store_id);
	my $on_going_count= scalar (@$on_going);

	my $taobao_oauth_url = $c->config->{taobao_oauth_url};
	my $redirect_uri = $c->config->{redirect_uri};
        my $response_type = $c->config->{response_type};
        my $scope = $c->config->{scope};
        my $view = $c->config->{view};
        my $app_key = $c->config->{app_key};
        my $taobao_login = $taobao_oauth_url . "?response_type=" . $response_type . "&client_id=" . $app_key . "&redirect_uri=" . $redirect_uri . "&scope=" . $scope . "&view=" . $view;
	my $buyer_size = scalar($c->stash->{object}->buyers);


	$c->stash(login_user => $c->session->{login_user});
        $c->stash(
		store => $c->stash->{object},
		login_user_role=>$login_user_role,
		buyer_size => $buyer_size,
		taobao_login => $taobao_login,
		out_of_dates_count => $out_of_dates_count,
		shenpi_count => $shenpi_count,
		zhuangtai => $zhuangtai,
		shenpi => $shenpi,
		on_going_count => $on_going_count,
		on_going => $on_going,
		out_of_dates => $out_of_dates,
		css => 'store_mainpage.css',
		javascript => '/store/store_info.js',
                template => 'stores/store_mainpage.tt2');
}

sub comments_total:Local {
        my ($self, $c) = @_;

        my $store_id = $c->request->params->{store_id};
        my $store= $c->model('Store::StoreSearchModel')->find($store_id);
        $c->res->output($c->model('Comments::CommentsForStoreModel')->get_comm_count($store->comm_item_id));
}

sub comments_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $store_id = $c->request->params->{store_id};

	my $owner_id = $c->model('UserStore::UserStoreModel')->get_owner($store_id)->get_column("user_id")->first();					
        my $store= $c->model('Store::StoreSearchModel')->find($store_id);
        my $page = $start_index / 10;
        $page = $page + 1;
        $c->stash(
                nowrapper => 1,
		owner_id => $owner_id,
                template => 'stores/user_comments.tt2',
        	comments => $c->model('Comments::CommentsForStoreModel')->search($store->comm_item_id, $page));
}



sub comment:Chained('base') :PathPart('comment') :Args(0){
        my ( $self, $c ) = @_;
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                return 0;
        }

        my $comment = $c->request->params->{comment} || '';
        my $comm_id= $c->request->params->{comm_id} || '';
        my $store_id= $c->request->params->{store_id} || '';
        my $store= $c->model('Store::StoreSearchModel')->find($store_id);
        $c->model('CommentedItem::CommentedItemModel')->add_to_comments($comm_id, $c->user->get('id'), $comment);
        $c->user->add_to_my_news({user_id=>$c->user->id, event_type_id=>6, photo=>$c->user->photo, me_name=>$c->user->username, target_id=>$store_id, target_name=>$store->name});
	$c->res->output('1');
}

sub uploadImage:Local{
	my ($self, $c) = @_;
	my $upload = $c->request->upload('imgFile');
	my $file = $c->model('Store::StoreCreateModel')->imgUpload($c->config->{image_path}, $upload);
	my $host_uri = $c->config->{host_uri};
	my $return = "{\"imgUrl\":\"$host_uri/static/images/big/$file\"}";
	$c->res->output($return);
}

=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
